﻿package {
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	public class Squids extends Sprite {
		[Embed(source='Ocean3.jpg')]
		private var Background:Class;
		private var background:Bitmap;
		
		private static const RANDOM_TARGETS:int = 1;
		
		private var w:Number = 800;
		private var h:Number = 600;
		
		private var squids:Vector.<Squid> = new Vector.<Squid>();
		private var time:Number = 0;
		
		private var mode:int = RANDOM_TARGETS;
		
		public function Squids():void {
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		private function init(e:Event = null):void {
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			/*
			var s:Squid = new Squid(100, 100);
			squids.push(s);
			addChild(s);
			*/
			
			stage.scaleMode = StageScaleMode.NO_SCALE;
			
			addChild(background = new Background()); background.x = w/2-background.width/2; background.y = h/2-background.height/2;
			
			for (var i:int = 0; i < 2; i++) {
				var s:Squid = new Squid(Math.random()*w, Math.random()*h, new Rectangle(50, 50, w-100, h-100));
				squids.push(s);
				addChild(s);
			}
			
			addEventListener(Event.ENTER_FRAME, run);
		}
		
		private function run(e:Event):void {
			for (var i:int = 0; i < squids.length; i++) {
				var s:Squid = squids[i];
				var bp:Point = background.globalToLocal(s.position);
				s.setColor(background.bitmapData.getPixel(bp.x, bp.y));
				s.update();
				if (s.nextTarget) {
					if (i == 0) {
						s.setTarget(mouseX, mouseY);
						//s.target.x = mouseX;
						//s.target.y = mouseY;
					} else {
					s.nextTarget = false;
					if (Math.random() < 0.8) {
						s.randomizeTarget();
						//s.targetTimeout = Math.random()*600;
						s.targetTimeout = -1;
					} else {
						/*
						var q:Squid = i == 0 ? squids[1] : squids[0];
						var randomAngle:Number = Math.random()*Math.PI*2;
						var randomRadius:Number = Math.random()*50;
						s.target.x = q.x+Math.cos(randomAngle)*randomRadius;
						s.target.y = q.y+Math.sin(randomAngle)*randomRadius;
						*/
						var q:Squid = i == 0 ? squids[1] : squids[0];
						
						//s.target = q.position;
						s.originalTarget = q.position;
						
						//s.targetTimeout = Math.random()*1800;
						s.targetTimeout = 300+Math.random()*2000;
					}
					}
					
					//s.target.x += ((q.x+Math.cos(randomAngle)*randomRadius)-s.target.x)*0.1;
					//s.target.y += ((q.y+Math.sin(randomAngle)*randomRadius)-s.target.y)*0.1;
				}
			}
			
			time++;
		}
	}
}